import React, { Component } from 'react';
import { connect } from 'dva';
import { Form, Divider, Badge } from 'antd';
import { withRouter } from 'umi';
import moment, { isDate } from 'moment';
import StandardTable from '@/components/StandardTable';
import AntdInput from '@/components/AntdInput';
import AdSelect from '@/components/AdSelect';
import AntdForm from '@/components/AntdForm';
import AntdFormItem from '@/components/AntdFormItem';
import AntdDatePicker from '@/components/AntdDatePicker';
import FileReader from '@/components/FileReader';
import AntdSelectRegion from '@/components/AntdSelectRegion';
import SearchSelect from '@/components/SearchSelect';
import { allDictList } from '@/utils/constans';
import { queryDict, filterAddFile, filterDeteteFile, formatPrice } from '@/utils/common';
import { columnsDriver } from '@/pages/Common/common';
import { selectArchivesDetailAndInfo, allDispatchType, renderTableAdSelect, codes } from './utils';
import styles from './archives.less';

const dateFormat = 'YYYY-MM-DD';

@connect(({ Archives, component, loading }) => ({
    dictObject: component.dictObject,
    

    incidentalInfoList: Archives.incidentalInfoList,
    loading: loading.effects[allDispatchType.incidentalInfo],
}))
@Form.create()
@withRouter
export default class PartsOfferInfo extends Component {
    constructor(props) {
        super(props);
        const {
            form: { getFieldDecorator },
        } = props;
        this.state = {
            detailId: '',
            isHK:false,
        };
        this.commonParams = {
            getFieldDecorator,
        };
    }
   
    

    componentWillMount() {
        const { dispatch, trainId } = this.props;
        this.saveAllValue({ incidentalInfoList: { [trainId]: { list: [] } } });
        const allDict = [allDictList.currencyType, allDictList.otherFeeType, allDictList.costSubjects,allDictList.costTag];
        queryDict({ props: this.props, allDict });
    }

    componentDidMount() {
        const { trainId, incidentalInfoList, onRef ,isHK} = this.props;
        const id = trainId;
        onRef && onRef(this);
        if (!id) return;
        this.handleStateChange([{ detailId: id }]);
        const detail = incidentalInfoList[id];
        // if (detail) return;
        this.incidentalInfoList(id);
        this.setState({isHK})
    }

    componentWillReceiveProps(nextProps, nextState) {
        const { trainId, incidentalInfoList } = nextProps;
        const id = trainId;
        const { detailId } = nextState;
        if (
            !id &&
            !this.state.detailId &&
            (!detailId || (detailId && detailId === '')) &&
            !incidentalInfoList[this.state.detailId]
        ) {
            this.saveAllValue({
                incidentalInfoList: { [this.state.detailId]: { list: [this.getAddDataObj()] } },
            });
        }
        if (this.props.trainId !== id) {
            this.handleStateChange([{ detailId: id }]);
            this.incidentalInfoList(id);
        }
    }

    incidentalInfoList = (id, callback) => {
        const { dispatch } = this.props;
        dispatch({
            type: allDispatchType.incidentalInfoList,
            payload: { id },
            callback: data => {
                let newData = data;
                newData.map(v => {
                    if (v.attaQuantity > 0) {
                        dispatch({
                            type: allDispatchType.selectFileList,
                            payload: { bizId: v.id, fileBizType: 'MISCELLANEOUS' },
                            callback: data => {
                                v.fileList = data;
                                this.saveAllValue({
                                    incidentalInfoList: { [this.state.detailId]: { list: newData } },
                                });
                            },
                        });
                    }
                });
            },
        });
    };

    getAddDataObj = () => {
        return {
            id: `isNew${Math.ceil(Math.random() * 10000) + 10000}`,
            miscellaneousNo: '',
            type: '',
            happenTime: '',
            fee: '',
            currency: '',
            remark: '',
            fileTokens: [],
            driverId: '',
        };
    };

    addInfoInd = () => {
        const { detailId } = this.state;
        let newData = this.getInfoData();
        newData = [this.getAddDataObj(), ...newData];
        this.saveAllValue({ incidentalInfoList: { [detailId]: { list: newData } } });
    };

    getInfoData = () => {
        const { incidentalInfoList } = this.props;
        const { detailId } = this.state;
        let newData = [];
        if (incidentalInfoList[detailId]) {
            const data = incidentalInfoList[detailId].list;
            newData = data.map(item => ({ ...item }));
            console.log('newData====',newData)
        }
        return newData;
    };

    getRowByKey(id, newData) {
        const data = this.getInfoData();
        return (newData || data).filter(item => item.id === id)[0];
    }

    handleFieldChange(value, fieldName, id, fieldName2) {
        const { detailId } = this.state;
        const { dispatch, showTipsFun,dictObject,form } = this.props;
        showTipsFun(true);
        const newData = this.getInfoData();
        const target = this.getRowByKey(id, newData);
        if (target) {
            target[fieldName] = value;
        }
        //费用类型带出 科目
        if (fieldName === 'type') {
            let obj = dictObject[allDictList.otherFeeType].find(item => item.code === value)
            // 因为手动选择的优先级大于自动带出的默认的值， 所以当 costType被手动选择后，再点费用类型会带不出科目；需要调用
           // form.setFieldsValue去手动设置表格中 的显示的值
            form.setFieldsValue({ [`costType-${target.id}`]: obj.remarks });
           // 表格中设置显示 值后，需要把设置的值保存到 后台
            target.costType = obj.remarks;
        }
        if (fieldName === 'happenTime') {
            if (value) {
                target.happenTime = moment(value).format(dateFormat);
            }
        } else if (fieldName === 'fileTokens') {
            target.fileTokens = filterAddFile(value) || [];
            target.deleteFileIds = filterDeteteFile(value, target.fileList || []) || []; //测试
        }
        if (fieldName == 'driverId') {
            target[fieldName] = value[0].id;
            target[fieldName2] = value;
        }

        this.saveAllValue({ incidentalInfoList: { [detailId]: { list: newData } } });
    }

    saveAllValue = payload => {
        const { dispatch } = this.props;
        dispatch({
            type: allDispatchType.value,
            payload: payload || {},
        });
    };

    handleStateChange = (options = []) => {
        options.map(item => {
            this.setState(item);
        });
    };

    render() {
        const {
            incidentalInfoList,
            loading,
            onSelectRow,
            selectedRows,
            trainId,
            disabled,
            countFee,
            onlyRead,
            incidentalData,
        } = this.props;
        const { detailId,isHK } = this.state;

        const data = incidentalData
            ? incidentalData[detailId] || {}
            : incidentalInfoList[detailId] || {};
        let columns = [
            {
                title: '单据号',
                dataIndex: 'miscellaneousNo',
                width: 140,
                render: (text, record) => {
                    const { dictObject, onlyRead, disabled } = this.props;
                    if (!onlyRead) {
                        return (
                            <AntdFormItem
                                label=" "
                                code={`miscellaneousNo-${record.id}`}
                                initialValue={text}
                                {...this.commonParams}
                            >
                                <AntdInput
                                    disabled={true}
                                    onChange={value => this.handleFieldChange(value, 'miscellaneousNo', record.id)}
                                    placeholder="保存后系统自动生成"
                                />
                            </AntdFormItem>
                        );
                    }
                    return <span>{text}</span>;
                },
            },
            {
                title:'是否已生成账单',
                dataIndex:'isBill',
                width:130,
                render:(text,record)=>{
                    const { dictObject, onlyRead, disabled } = this.props;
                    if (!onlyRead) {
                        return (
                            <AntdFormItem
                                label=" "
                                code={`isBill-${record.id}`}
                                initialValue={text}
                                {...this.commonParams}
                            >
                                <AntdInput
                                    disabled={true}
                                    onChange={value => this.handleFieldChange(value, 'isBill', record.id)}
                                    placeholder="保存后系统自动生成"
                                />
                            </AntdFormItem>
                        );
                    }
                    return <span>{text==='true'?'是':'否'}</span>;
                }
            },
            {
                title: '费用类型',
                dataIndex: 'type',
                width: 130,
                render: (text, record) => {
                    const { dictObject, onlyRead, disabled } = this.props;
                    if (!onlyRead) {
                        return (
                            <AntdFormItem
                                label=" "
                                code={`type-${record.id}`}
                                initialValue={text}
                                {...this.commonParams}
                                rules={[{ required: true }]}
                            >
                                <AdSelect
                                    disabled={disabled}
                                    isExist={true}
                                    data={dictObject[allDictList.otherFeeType]}
                                    payload={{ code: allDictList.otherFeeType }}
                                    onChange={value => this.handleFieldChange(value, 'type', record.id)}
                                />
                            </AntdFormItem>
                        );
                    }
                    return renderTableAdSelect({
                        props: this.props,
                        value: text,
                        key: allDictList.otherFeeType,
                    });
                },
            },
            {
                title: '科目',
                dataIndex: 'costType',
                width: 200,
                render: (text, record) => {
                    const { dictObject, onlyRead, disabled } = this.props;
                    if (!onlyRead) {
                        return (
                            <AntdFormItem
                                label=" "
                                code={`costType-${record.id}`}
                                initialValue={text}
                                {...this.commonParams}
                                rules={[{ required: true }]}
                            >
                                <AdSelect
                                    disabled={disabled}
                                    isExist={true}
                                    data={dictObject[allDictList.costSubjects]}
                                    payload={{ code: allDictList.costSubjects }}
                                    onChange={value => this.handleFieldChange(value, 'costType', record.id)}
                                />
                            </AntdFormItem>
                        );
                    }
                    return renderTableAdSelect({
                        props: this.props,
                        value: text,
                        key: allDictList.costSubjects,
                    });
                },
            },
            isHK?{
                title: '费用标识',
                dataIndex: 'costTag',
                width: 230,
                render: (text, record) => {
                    const { dictObject, onlyRead, disabled } = this.props;
                    if (!onlyRead) {
                        return (
                            <AntdFormItem
                                label=" "
                                code={`costTag-${record.id}`}
                                initialValue={text}
                                {...this.commonParams}
                                rules={[{ required: true }]}
                            >
                                <AdSelect
                                    disabled={disabled}
                                    isExist={true}
                                    // multiple={true}
                                    // mode="multiple"
                                    data={dictObject[allDictList.costTag]}
                                    payload={{ code: allDictList.costTag}}
                                    onChange={value => this.handleFieldChange(value, 'costTag', record.id)}
                                />
                            </AntdFormItem>
                        );
                    }
                    return renderTableAdSelect({
                        props: this.props,
                        value: text,
                        key: allDictList.costTag,
                    });
                },
            }:{},
            {
                title: '时间',
                dataIndex: 'happenTime',
                width: 140,
                render: (text, record) => {
                    const { dictObject, onlyRead, disabled } = this.props;
                    if (!onlyRead) {
                        return (
                            <AntdFormItem
                                label=" "
                                code={`happenTime-${record.id}`}
                                initialValue={text ? moment(text, dateFormat) : null}
                                {...this.commonParams}
                                rules={[{ required: true }]}
                            >
                                <AntdDatePicker
                                    disabled={disabled}
                                    onChange={value => this.handleFieldChange(value, 'happenTime', record.id)}
                                />
                            </AntdFormItem>
                        );
                    }
                    return <span>{text}</span>;
                },
            },
            {
                title: '司机',
                dataIndex: 'driverId',
                width: 160,
                render: (text, record) => {
                    const { dictObject, onlyRead, disabled } = this.props;
                    if (!onlyRead) {
                        return (
                            <AntdFormItem
                                label=" "
                                code={`driverId-${record.id}`}
                                initialValue={record.driverId ? [{ id: record.driverId }] : ''}
                                rules={[{ required: true }]}
                                {...this.commonParams}
                            >
                                <SearchSelect
                                    dataUrl="tms/tms-driver-archives/selectDriverList"
                                    url="tms/tms-driver-archives/selectDriverView_s"
                                    multiple={false} // 是否多选
                                    selectedData={record.drivers || [{ id: record.driverId }]} // 选中值
                                    columns={columnsDriver} // 表格展示列
                                    onChange={value => this.handleFieldChange(value, 'driverId', record.id, 'drivers')}
                                    id="ArchivesOperate_2"
                                    disabled={disabled}
                                    allowClear={false}
                                />
                            </AntdFormItem>
                        );
                    }
                    return <span>{record.driverName}</span>;
                },
            },
            {
                title: '金额(元)',
                dataIndex: 'fee',
                width: 120,
                render: (text, record) => {
                    const { onlyRead, disabled } = this.props;
                    if (!onlyRead) {
                        return (
                            <AntdFormItem
                                label=" "
                                code={`fee-${record.id}`}
                                initialValue={formatPrice(text)}
                                {...this.commonParams}
                                rules={[{ required: true }]}
                            >
                                <AntdInput
                                    mode="money"
                                    disabled={disabled}
                                    onChange={value => this.handleFieldChange(value, 'fee', record.id)}
                                />
                            </AntdFormItem>
                        );
                    }
                    return formatPrice(text);
                },
            },
            {
                title: '币种',
                dataIndex: 'currency',
                width: 130,
                render: (text, record) => {
                    const { dictObject, onlyRead, disabled } = this.props;
                    if (!onlyRead) {
                        return (
                            <AntdFormItem
                                label=" "
                                code={`currency-${record.id}`}
                                initialValue={'CNY'}
                                {...this.commonParams}
                                rules={[{ required: true }]}
                            >
                                <AdSelect
                                    disabled={disabled}
                                    data={dictObject[allDictList.currencyType]}
                                    payload={{ code: allDictList.currencyType }}
                                    onChange={value => this.handleFieldChange(value, 'currency', record.id)}
                                />
                            </AntdFormItem>
                        );
                    }
                    return renderTableAdSelect({
                        props: this.props,
                        value: text,
                        key: allDictList.currencyType,
                    });
                },
            },
            {
                title: '备注',
                dataIndex: 'remark',
                width: 150,
                render: (text, record) => {
                    const { onlyRead, disabled } = this.props;
                    if (!onlyRead) {
                        return (
                            <AntdInput
                                value={text}
                                disabled={disabled}
                                node="number"
                                onChange={value => this.handleFieldChange(value, 'remark', record.id)}
                            />
                        );
                    }
                    return text;
                },
            },
            {
                title: '附件',
                dataIndex: 'fileTokens',
                 width: 200,
                render: (text, record) => {
                    const { onlyRead, disabled } = this.props;
                    const _text = record.attaQuantity;
                    if (!onlyRead) {
                        return (
                            <AntdFormItem
                                label=" "
                                code={`fileTokens-${record.id}`}
                                initialValue={record.fileList || []}
                                {...this.commonParams}
                            >
                                <FileReader
                                    urlType="tms"
                                    onChange={value => this.handleFieldChange(value, 'fileTokens', record.id)}
                                    disabled={disabled}
                                />
                            </AntdFormItem>
                        );
                    }
                    return (
                        _text &&
                        Number(_text) > 0 && (
                            <Badge className="cus_badge" count={_text}>
                                <div className="head-example">
                                    <FileReader
                                        type="list"
                                        count={_text}
                                        urlType="tms"
                                        params={{ bizId: record.id, fileBizType: 'MISCELLANEOUS' }}
                                    />
                                </div>
                            </Badge>
                        )
                    );
                },
            },
        ];
        return (
            <div className={styles.customPartsOfferInfo}>
                {countFee == 0 && onlyRead ? (
                    <div style={{ textAlign: 'left', marginLeft: '30vw' }}>暂无数据</div>
                ) : (
                        <AntdForm>
                            <StandardTable
                                loading={loading}
                                data={data}
                                columns={columns}
                                selectedRows={selectedRows}
                                disabledRowSelected={onlyRead || disabled}
                                pagination={false}
                                scrollX={1200}
                                scrollY={200}
                                canInput={true}
                                onSelectRow={selectedRows => {
                                    onSelectRow(selectedRows);
                                }}
                            />
                        </AntdForm>
                    )}
            </div>
        );
    }
}
